<template>
  <div>
    <h5 class="text-muted">当前任务：审批登记</h5>
    <el-form class="query-form" @submit.native.prevent :inline="true" :model="params">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          :clearable="true"
          placeholder="企业名称查询"
          @change="getData"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-checkbox
          v-model="params.has_ele_fee"
          v-if="!showImportBtn"
          border
          :true-label="1"
          false-label=""
          @change="getData"
        >
          有电表
        </el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button @click="getData()" v-if="!showImportBtn">查询</el-button>
        <el-button @click="getOneIndustry" v-else>查询</el-button>
      </el-form-item>
      <el-form-item class="float-right" v-if="showImportBtn">
        <el-button type="primary" class="btn-long" @click="showDialogImport">
          导入十二大产业贷
        </el-button>
      </el-form-item>
      <el-form-item class="float-right" style="margin-right: 50px" v-if="1">
        <el-badge :value="oneIndustryTotalCount" type="primary" class="item">
          <el-button class="btn-long" @click="getOneIndustryView" v-loading="loading">
            十二大产业贷
          </el-button>
        </el-badge>
      </el-form-item>
    </el-form>
    <loading-wrap>
      <el-table border :data="tableData" v-show="!showImportBtn">
        <el-table-column
          label="放款通知书编号"
          min-width="120"
          prop="loan_notice"
        ></el-table-column>
        <el-table-column label="企业名称" min-width="180" prop="customer_name"></el-table-column>
        <el-table-column label="法人" prop="corp_name"></el-table-column>
        <el-table-column label="联系电话" min-width="100" prop="mobile_no"></el-table-column>
        <el-table-column label="贷款时间" min-width="85">
          <template slot-scope="scope">
            {{ $utils.dateFormat(scope.row.load_date, 'yyyy.MM.dd') }}
          </template>
        </el-table-column>
        <el-table-column
          label="担保期限(年)"
          min-width="60"
          align="center"
          prop="warranty_period"
        ></el-table-column>

        <el-table-column label="分配时间" min-width="85">
          <template slot-scope="scope">
            <span>{{ scope.row.taskAssginDate }}</span>
          </template>
        </el-table-column>

        <el-table-column label="调查完成时间" min-width="85">
          <template slot-scope="scope">
            <span>{{ scope.row.taskCompleteDate }}</span>
          </template>
        </el-table-column>

        <el-table-column label="完成天数" align="right">
          <template slot-scope="scope">
            <span>{{ scope.row.completeDays }}</span>
          </template>
        </el-table-column>

        <el-table-column label="到期时间" min-width="85">
          <template slot-scope="scope">
            {{ $utils.dateFormat(scope.row.load_end_date, 'yyyy.MM.dd') }}
          </template>
        </el-table-column>
        <el-table-column label="审批金额（万元）" min-width="85">
          <template slot-scope="scope">
            <span>{{ scope.row.reply_funds }}</span>
          </template>
        </el-table-column>

        <el-table-column label="审批状态" prop="apply_funds">
          <template slot-scope="scope">
            <span :class="`text-${enumApprovalStatus[scope.row.approval_register_status].css}`">
              {{ enumApprovalStatus[scope.row.approval_register_status].label }}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="100">
          <template slot-scope="scope">
            <el-button
              class="py-0 px-2"
              v-if="!powerHide"
              type="text"
              @click="goregister(scope.row)"
            >
              <i class="fa fa-edit"></i>
            </el-button>
            <el-button class="py-0 px-2" type="text" @click="goregister(scope.row, true)">
              <i class="fa fa-search"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="query-pagination" v-show="!showImportBtn">
        <el-pagination
          layout="total, prev, pager, next, jumper"
          :current-page.sync="params.index"
          :page-size="params.size"
          :total="totalCount"
          @current-change="getData"
        ></el-pagination>
      </div>
      <el-table border :data="oneIndustryTableData" v-show="showImportBtn">
        <el-table-column label="借款人/担保客户" prop="customer_name"></el-table-column>
        <el-table-column label="客户类型" prop="org_class_name"></el-table-column>
        <el-table-column label="主营业务" prop="main_budiness"></el-table-column>
        <el-table-column label="联系电话" prop="corp_phone"></el-table-column>
        <el-table-column label="放款日/拟担保起始日">
          <template slot-scope="scope">
            <span>{{ $utils.dateFormat(scope.row.load_date, 'yyyy-MM-dd') || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="到期日">
          <template slot-scope="scope">
            <span>{{ $utils.dateFormat(scope.row.load_end_date, 'yyyy-MM-dd') || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="贷款期限" prop="warranty_period"></el-table-column>
        <el-table-column
          label="审批金额（万元）"
          prop="warranty_amount"
          align="right"
        ></el-table-column>
        <el-table-column label="审批状态">已通过</el-table-column>

        <el-table-column label="操作" min-width="80">
          <template slot-scope="scope">
            <el-button class="py-0 px-2" type="text" @click="goOneIndustry(scope.row)">
              <i class="fa fa-search"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="query-pagination" v-show="showImportBtn">
        <el-pagination
          layout="total, prev, pager, next, jumper"
          :current-page.sync="params.index"
          :page-size="params.size"
          :total="oneIndustryTotalCount"
          @current-change="getOneIndustry"
        ></el-pagination>
      </div>
    </loading-wrap>
    <el-dialog
      top="130px"
      width="80%"
      :close-on-click-modal="false"
      :before-close="handleClose"
      :visible.sync="regVisible"
    >
      <!--<h5>项目编号：-->
      <!--<span v-if="number">{{number}}</span>-->
      <!--<span v-else-->
      <!--class="d-print-none">-->
      <!--<el-tooltip class="item"-->
      <!--effect="dark"-->
      <!--content="调查报告完成后，项目编号自动生成"-->
      <!--placement="bottom">-->
      <!--<el-button type="text"-->
      <!--class="text-muted">待定 <i class="fa fa-question-circle"></i></el-button>-->
      <!--</el-tooltip>-->
      <!--</span>-->
      <!--</h5>-->

      <div style="font-size: 1.25rem; display: flex">
        <span>项目编号：</span>
        <div v-if="!view" class="d-flex" style="max-width: 200px">
          <span>{{ censusNumberPrefix }}</span>
          <span>-</span>
          <input
            style="
              display: inline-block;
              padding: 0;
              border: none;
              background-color: #ffffee;
              width: 60px;
              text-align: center;
              font-size: 1.25rem;
              height: 26px;
            "
            class="form-control"
            placeholder="XXXX"
            v-model="censusNumberYear"
            @input="onCensusNumberYearInput"
          />
          <span>-</span>
          <input
            style="
              display: inline-block;
              padding: 0;
              border: none;
              background-color: #ffffee;
              width: 50px;
              text-align: center;
              font-size: 1.25rem;
              height: 26px;
            "
            class="form-control"
            placeholder="XXX"
            ref="censusNumberSerial"
            v-model="censusNumberSerial"
            @input="onCensusNumberSerialInput"
          />
        </div>
        <span v-else>{{ fillData.loan_notice }}</span>
      </div>

      <table class="table table-bordered">
        <colgroup>
          <col width="12%" />
          <col width="13%" />
          <col width="12%" />
          <col width="13%" />
          <col width="12%" />
          <col width="13%" />
          <col width="12%" />
          <col width="13%" />
        </colgroup>
        <tbody>
          <tr>
            <td>项目名称</td>
            <td>{{ fillData.customer_name }}</td>
            <td>贷款金额(万元)</td>
            <td class="input-td">
              <span v-if="view" class="px-2">{{ fillData.reply_funds }}</span>
              <el-input
                v-model="fillData.reply_funds"
                type="number"
                step="0.01"
                min="0"
                v-else
              ></el-input>
            </td>
            <td>用款期限</td>
            <td class="input-td">
              <span v-if="repayListExist" class="px-2">{{ fillData.warranty_period }}</span>
              <el-input-number
                v-model="fillData.warranty_period"
                v-else
                style="width: 70%"
                :controls="false"
                :min="0"
              ></el-input-number>
              年
            </td>
            <td>合作银行</td>
            <td v-if="view" class="px-2">{{ fillData.bank_name }}</td>
            <td v-else class="input-td">
              <!--<select-bank v-model="fillData.bank_name" @change="setName" class="w-100"></select-bank>-->
              <select-agency-info
                v-model="fillData.bank_code"
                @change="setName"
              ></select-agency-info>
            </td>
          </tr>
          <tr>
            <td>主审</td>
            <td class="input-td">
              <span v-if="view" class="px-2">{{ fillData.project_chief }}</span>
              <select-staff
                v-else
                ref="chief"
                @change="chief"
                v-model="fillData.project_chief"
              ></select-staff>
              <!--<el-input v-model="fillData.project_chief " v-else></el-input>-->
            </td>

            <td>主审意见</td>
            <td colspan="5" class="input-td">
              <span v-if="view" class="px-2">{{ fillData.approval_option }}</span>
              <el-input v-model="fillData.approval_option" v-else></el-input>
            </td>
          </tr>
          <tr>
            <td>辅审</td>
            <td class="input-td">
              <span v-if="view" class="px-2">{{ fillData.project_aux }}</span>
              <select-staff
                v-else
                ref="aux"
                @change="aux"
                v-model="fillData.project_aux"
              ></select-staff>
              <!--<el-input v-model="fillData.project_chief " v-else></el-input>-->
            </td>

            <td>辅审意见</td>
            <td colspan="5" class="input-td">
              <span v-if="view" class="px-2">{{ fillData.risk_option }}</span>
              <el-input v-model="fillData.risk_option" v-else></el-input>
            </td>
          </tr>

          <tr>
            <td>委托合同</td>
            <td class="input-td">
              <span v-if="view" class="px-2">{{ fillData.com_contract }}</span>
              <el-input v-model="fillData.com_contract" v-else></el-input>
            </td>
            <td>借款合同</td>
            <td class="input-td">
              <span v-if="view" class="px-2">{{ fillData.load_contract }}</span>
              <el-input v-model="fillData.load_contract" v-else></el-input>
            </td>
            <td>保证合同</td>
            <td class="input-td">
              <span v-if="view" class="px-2">{{ fillData.gua_contract }}</span>
              <el-input v-model="fillData.gua_contract" v-else></el-input>
            </td>
            <td>反担保合同</td>
            <td class="input-td">
              <span v-if="view" class="px-2">{{ fillData.warranty_contract }}</span>
              <el-input v-model="fillData.warranty_contract" v-else></el-input>
            </td>
          </tr>
          <tr>
            <td>贷款日期</td>
            <td class="input-td">
              <span v-if="repayListExist" class="px-2">
                {{ $utils.dateFormat(fillData.load_date, 'yyyy.MM.dd') }}
              </span>
              <el-date-picker
                v-model="fillData.load_date"
                v-else
                placeholder="项目贷款日期"
                style="width: 140px"
                type="date"
                value-format="yyyy-MM-dd"
                :clearable="true"
              ></el-date-picker>
            </td>
            <td>到期日期</td>
            <td class="input-td">
              <span v-if="repayListExist" class="px-2">
                {{ $utils.dateFormat(fillData.load_end_date, 'yyyy.MM.dd') }}
              </span>
              <el-date-picker
                v-model="fillData.load_end_date"
                v-else
                placeholder="项目到期日期"
                style="width: 140px"
                type="date"
                value-format="yyyy-MM-dd"
                :clearable="true"
              ></el-date-picker>
            </td>

            <td>担保意向涵</td>
            <td>
              <span>{{ this.number }}</span>
            </td>

            <td>还款方式</td>
            <td class="input-td">
              <span v-if="view" class="px-2">{{ fillData.repay_method }}</span>
              <el-input v-model="fillData.repay_method" v-else></el-input>
            </td>
          </tr>
          <tr>
            <td>放款通知书</td>
            <td colspan="2">
              <!--<span v-if="view">{{fillData.loan_notice}}</span>-->
              <!--<el-input v-model="fillData.loan_notice"-->
              <!--v-else></el-input>-->
              <span>铜农担放款通字〔</span>
              <span>{{ this.censusNumberYear }}</span>
              <span>〕第</span>
              <span>{{ this.censusNumberSerial }}</span>
              <span>号</span>
            </td>
            <td>备注</td>
            <td colspan="4" class="input-td">
              <span v-if="view" class="px-2">{{ fillData.remark }}</span>
              <el-input v-model="fillData.remark" v-else></el-input>
            </td>
          </tr>

          <tr>
            <td colspan="2">还款设置（APP端还款提示设置）</td>
            <td colspan="7">
              <div v-if="repayListExist" class="row">
                <div class="col d-flex align-items-center">
                  <span>{{ enumRepayType[fillData.repay_type] || '-' }}</span>
                </div>
                <div class="col">
                  <el-button @click="showViewRepayList">查看还款计划</el-button>
                </div>
              </div>
              <div class="row" v-else>
                <div class="col d-flex align-items-center">
                  <el-radio-group v-model="repayType" @change="onRepayTypeChange">
                    <el-radio v-for="(value, key) in enumRepayType" :label="key" :key="key">
                      {{ value }}
                    </el-radio>
                  </el-radio-group>
                </div>
                <div class="col">
                  <el-button @click="showRepayList">生成还款计划</el-button>
                </div>
              </div>
              <!-- <div style="text-align:center">
                <input type="radio"
                       v-model="fillData.repay_type"
                       value="1" /><span class="span-margin-min">按月还款</span>
                <input type="radio"
                       v-model="fillData.repay_type"
                       value="2" /><span class="span-margin">按季度还款</span>
                <span class="span-margin-min">每月/季度</span>
                <el-input v-model="fillData.repay_day"
                          type="number"
                          min="1"
                          max="31"
                          step="1"
                          class="input-min"></el-input>
                <span class="span-margin">号</span>
                <span>还款金额</span>
                <el-input type="number"
                          v-model="fillData.repay_funds"
                          min="0"
                          step="0.01"
                          class="input-min"></el-input>
                元

              </div> -->
            </td>
          </tr>
          <tr>
            <td colspan="8">
              <div style="page-break-after: always">
                <h3 class="report-section-title">附件</h3>

                <div v-if="!hasFinish">
                  <upload-oss
                    multiple
                    accept="image/*"
                    listType="picture-card"
                    :limit="10"
                    :file-list="attachFileList"
                    :on-complete="handleImagesComplete"
                    :on-exceed="handleOnExceed"
                    :on-remove="handleRemove"
                    auto-upload
                    ref="attachOss"
                  ></upload-oss>
                </div>

                <div v-else>
                  <div v-for="(img, index) in attachFileList" :key="index" class="mb-1 text-center">
                    <img :src="img.url" alt="附件图片" height="400" style="max-width: 100%" />
                  </div>
                </div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      <el-row class="row-bg" v-if="!view" justify="center" style="margin-top: 30px" type="flex">
        <el-col :span="6">
          <el-button style="margin-left: 15%" type="warning" @click="submit('2')">拒绝</el-button>
        </el-col>
        <el-col :span="6">
          <el-button style="margin-left: 10%" type="primary" @click="submit('1')">通过</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog
      top="30px"
      width="1100px"
      append-to-body
      :visible.sync="oneIndustryVisible"
      :close-on-click-modal="false"
    >
      <industry-credit :oneIndustry="oneIndustry"></industry-credit>
    </el-dialog>
    <import-excel
      :visible.sync="dialogImportVisible"
      title="导入十二大产业贷信息"
      :post-api="postUrl"
      excel-template="/static/files/一县一业产业贷导入模板.xlsx"
      @success="colose"
    ></import-excel>

    <el-dialog
      top="30px"
      width="600px"
      append-to-body
      title="还款计划"
      class="dialog-sm"
      :close-on-click-modal="false"
      :before-close="onRepayClose"
      :visible.sync="repayVisible"
    >
      <el-table :data="viewRepayList" :height="dialogMaxheight" border v-if="repayListExist">
        <el-table-column label="还款时间" prop="pay_time" align="center"></el-table-column>
        <el-table-column label="是否还息" align="center">
          <template slot-scope="scope">
            <span>{{ enumRepayInterest[scope.row.is_interest] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="本金（万元）" prop="capital" align="center"></el-table-column>
      </el-table>

      <div v-else>
        <el-table :data="repayList" :height="dialogMaxheight" border cell-class-name="input-td">
          <el-table-column label="还款时间">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.pay_time"
                type="date"
                class="w-100 text-center"
                value-format="yyyy-MM-dd"
                format="yyyy年MM月dd日"
                :clearable="false"
                :placeholder="`选择${scope.$index === 0 ? '开始' : ''}还款时间`"
                @change="v => onSelectFirstRepayDate(v, scope.$index)"
              ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="是否还息">
            <template slot-scope="scope">
              <div v-if="isLastMonthAtQuarter(scope.row.pay_time)">
                <c-select v-model="scope.row.is_interest" :options="enumRepayInterest"></c-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="本金（万元）">
            <template slot-scope="scope">
              <div class="d-flex">
                <el-input
                  v-model="scope.row.capital"
                  type="number"
                  class="flex-1"
                  placeholder="输入本金"
                ></el-input>
                <div
                  class="auto-fill-icon"
                  title="自动填写到所有下面的列"
                  @click="onAutoFill(scope.row, scope.$index)"
                >
                  <i class="fa fa-fw fa-level-down"></i>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="row mt-3">
          <div class="col text-center">
            <el-button class="btn-long" @click="onRepayListDismiss">取消</el-button>
          </div>
          <div class="col text-center">
            <el-button class="btn-long" type="primary" @click="onRepayListFinsish">完成</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { deltaDay } from '@/common/plugins/tools/date'
import { arrayFromString } from '@vimi/utils-tool'
import IndustryCredit from '@/bank/components/IndustryCredit'
import { enumApprovalStatus, enumFarmType } from '@/credit/plugins/enum'
import SelectStaff from '@/components/select/SelectStaff'
import ImportExcel from '@/components/ImportExcel'
import { ONE_INDUSTRY_LOAD_PRODUCT } from '@/credit/plugins/constant'
import SelectAgencyInfo from '@/credit/components/select/SelectAgencyInfo'
const CREDIT_SERVER = 'credit'
const yearNow = new Date().getFullYear()

export default {
  components: {
    SelectAgencyInfo,
    // SelectBank,
    ImportExcel,
    SelectStaff,
    IndustryCredit,
  },
  props: {},
  data() {
    return {
      hasFinish: false,
      postUrl: '',
      loading: false,
      enumFarmType,
      dialogImportVisible: false,
      oneIndustryVisible: false,
      enumApprovalStatus,
      enumStatusType: {
        0: 'danger',
        1: 'success',
        2: 'warning',
      },
      // 一县一业产业贷
      showImportBtn: false,
      oneIndustryTotalCount: 0,
      oneIndustryTableData: [],
      oneIndustry: {},
      params: {
        index: 1,
        size: 10,
        customer_name: '',
        'project_status.eq': '3',
      },
      totalCount: 0,
      tableData: [],
      nbspArrStr: '',
      nbspArrLen: 20,
      status: '',
      relatedId: '',
      number: '',
      regVisible: false,
      view: false,
      fillData: {},
      chiefmain: '',
      // 附件
      attachFileList: [],
      // 编号
      censusNumberPrefix: 'TND',
      censusNumberYear: '',
      censusNumberSerial: '',
      // 还款计划
      viewRepayList: [],
      viewRepayListError: true,
      repayType: '',
      enumRepayType: {
        1: '按月还款',
        2: '按季度还款',
      },
      enumRepayInterest: {
        0: '否',
        1: '是',
      },
      repayList: [],
      repayVisible: false,
      repayLoading: false,
      repayPeriod: '',
      dialogMaxheight: 500,
    }
  },
  computed: {
    job() {
      return this.$store.getters.user.job
    },
    clientId() {
      return this.$store.getters.org.clientId
    },
    powerHide() {
      return (
        ['org_c_emp', 'org_r_manage', 'org_r_emp', 'org_p_manage', 'org_p_emp', 'org_corp'].indexOf(
          this.job
        ) > -1
      )
    },
    repayListExist() {
      return this.view || this.viewRepayListError || this.viewRepayList.length
    },
    repayMonthType() {
      return +this.fillData.repay_type === 1
    },
  },
  watch: {
    $route(route) {
      if (route.name === 'taskRegister') {
        this.status = this.$route.query.status
        if (this.status !== undefined) {
          this.params['approval_register_status.eq'] = this.status
        }
        this.getOneIndustry()
        this.getData()

        // this.showImportBtn = true
      }
    },
  },
  created() {
    this.initDialogMaxHeight()
    this.userId = this.$store.getters.user.userId
    this.params['service_id.eq'] = this.$store.getters.org.clientId
    this.fillData.service_id = this.$store.getters.org.clientId
    this.postUrl =
      '/api/credit/import/?importKey=datum_one_county_industry_template_credit&where=' +
      encodeURIComponent('"datum_one_county_industry.service_id".eq(' + this.clientId + ')')
    this.getData()
    this.getOneIndustry()
  },
  activated() {},
  mounted() {},
  methods: {
    setName(code, name) {
      this.fillData.bank_name = (name && name.length) > 0 ? name[name.length - 1] : ''
    },
    chief() {
      this.fillData.project_chief = this.$refs.chief.getSelectedName()
    },
    colose() {
      this.dialogImportVisible = false
      this.$store.dispatch('getTaskCount')
      this.getOneIndustry()
    },
    aux() {
      this.fillData.project_aux = this.$refs.aux.getSelectedName()
    },
    getData() {
      const params = { ...this.params }
      const status = this.$route.query.status
      if (status !== undefined) {
        params['approval_register_status.eq'] = status
      }
      params['submit_type.eq'] = 2
      params['loan_product_id.neq'] = ONE_INDUSTRY_LOAD_PRODUCT

      if (
        [
          'org_credit_super',
          'org_c_manage',
          'org_r_emp',
          'org_r_manage',
          'org_corp',
          'org_c_general', // 综合部负责人
        ].indexOf(this.job) < 0
      ) {
        params['orWhere.res_a.eq'] = this.userId
        params['orWhere.res_b.eq'] = this.userId
      }

      this.$api
        .getData('credit', 'customer_related_register_view', params, {
          loan_notice: 'desc',
        })
        .then(res => {
          this.tableData = ((res && res.data && res.data.data) || []).map(item => {
            item.taskAssginDate = this.$utils.dateFormat(item.task_assgin_date, 'yyyy.MM.dd')
            item.taskCompleteDate = this.$utils.dateFormat(item.task_complete_date, 'yyyy.MM.dd')
            const days = deltaDay(item.task_assgin_date, item.task_complete_date)
            item.completeDays = days ? `${days}天` : ''
            return item
          })
          this.totalCount = (res && res.data && res.data.totalCount) || 0
        })
    },
    getOneIndustryView() {
      this.showImportBtn = !this.showImportBtn
      this.getOneIndustry()
    },

    getOneIndustry() {
      this.params.has_ele_fee = ''
      this.status = this.$route.query.status
      if (this.status !== undefined) {
        this.params['approval_register_status.eq'] = this.status
      }
      this.$api
        .getData('credit', 'datum_one_county_industry', this.params, {
          create_time: 'desc',
        })
        .then(res => {
          this.oneIndustryTableData = (res && res.data && res.data.data) || []
          this.oneIndustryTotalCount = (res && res.data && res.data.totalCount) || 0
        })
    },
    goOneIndustry(row) {
      this.oneIndustry = row
      this.oneIndustryVisible = true
    },
    showDialogImport() {
      this.dialogImportVisible = true
    },

    goregister(row, view) {
      // init nbspArrStr
      // for (var i=0; i<this.nbspArrLen; i++ ) {

      //    this.nbspArrStr=this.nbspArrStr+'&nbsp'
      //  }
      this.censusNumberYear = ''
      this.censusNumberSerial = ''

      this.regVisible = true
      this.view = view
      this.number = ''
      this.relatedId = row.customer_related_id
      this.$api
        .getData(
          'credit',
          'credit_census_report',
          { 'customer_related_id.eq': row.customer_related_id },
          {
            create_time: 'desc',
          }
        )
        .then(res => {
          if (res && res.data) {
            this.number = res.data[0].census_number
          }
        })
      this.$api
        .getData(
          'credit',
          'credit_census_report_simple',
          { 'customer_related_id.eq': row.customer_related_id },
          {
            create_time: 'desc',
          }
        )
        .then(res => {
          if (res && res.data) {
            this.number = res.data[0].census_number
          }
        })
      this.$set(this.fillData, 'bank_name', row.bank_name)
      this.$set(this.fillData, 'bank_code', row.bank_code)
      this.$set(this.fillData, 'warranty_period', row.load_years)
      this.$set(this.fillData, 'reply_funds', row.approved_funds)
      // this.fillData.bank_code = row.bank_code
      if (row.customer_name) {
        this.fillData.customer_name = row.customer_name
      }
      if (row.id) {
        this.$api
          .getData(
            'credit',
            'credit_level_review',
            { 'id.eq': row.id },
            {
              create_time: 'desc',
            }
          )
          .then(res => {
            if (res && res.data && res.data.length) {
              this.fillData = res.data[0]
              this.repayType = this.fillData.repay_type
              // 附件图片
              this.attachFileList = arrayFromString(this.fillData.attachment).map(item => {
                return { name: '', url: item }
              })
            }

            if (row.customer_name) {
              this.fillData.customer_name = row.customer_name
            }
            // 编号
            if (this.fillData.loan_notice) {
              const arr = this.fillData.loan_notice.match(/\d+/g)
              if (arr && arr.length > 1) {
                this.censusNumberYear = arr[0]
                this.censusNumberSerial = arr[1]
              }
            }
          })
      }

      this.repayPeriod = row.warranty_period
      this.initRepayList()
      this.getRepayList()
    },
    handleClose() {
      this.fillData = {}
      this.regVisible = false
      this.getData()
    },
    postData(data) {
      this.$api
        .addData('credit', 'credit_level_review', data)
        .then(() => {
          this.$message.success('提交成功！')
          this.handleClose()
          this.getData()
          this.initRepayList()
          this.$store.dispatch('getTaskCount')
        })
        .catch(() => {
          this.$message.error('提交失败请重试！')
        })
    },
    putData(data) {
      this.$api
        .updateData('credit', 'credit_level_review', data.id, data)
        .then(() => {
          this.$message.success('提交成功！')
          this.handleClose()
          this.getData()
          this.initRepayList()
          this.$store.dispatch('getTaskCount')
        })
        .catch(() => {
          this.$message.error('提交失败请重试！')
        })
    },
    submit(val) {
      this.fillData.is_approval = val
      this.fillData.customer_related_id = this.relatedId

      if (!this.censusNumberYear) {
        return this.$message.error('请输入编号年份！')
      }
      const year = +this.censusNumberYear
      if (year > yearNow || year < yearNow - 1) {
        return this.$message.error('编号年份必须是今年或去年！')
      }
      if (!this.censusNumberSerial) {
        return this.$message.error('请输入编号！')
      }
      if (this.censusNumberSerial === '000') {
        return this.$message.error('编号必须大于0')
      }

      const num = `${this.censusNumberPrefix}-${
        this.censusNumberYear
      }-${this.getFullNumberSerial()}`
      this.validateCensusNumberFromRemote(num).then(res => {
        if (res >= 0 && res < 1) {
          this.fillData.loan_notice = num
          this.saveData()
        } else if (res >= 1 && !this.fillData.id) {
          this.$message.error('项目编号已经存在！')
        } else if (res === 1 && this.fillData.id) {
          this.fillData.loan_notice = num
          this.saveData()
        } else if (res > 1 && this.fillData.id) {
          this.$message.error('项目编号已经存在！')
        } else if (res === -1) {
          this.$message.error('项目编号验证失败！')
        }
      })
    },
    handleOnExceed() {
      this.$message.error('附件图片最多10张！')
    },

    handleRemove(file, fileList) {
      this.fillData.attachment = this.getImageString(fileList)
    },
    handleImagesComplete(images) {
      this.fillData.attachment = this.getImageString(images)
    },
    saveData() {
      if (this.fillData.id) {
        this.putData(this.fillData)
      } else {
        this.postData(this.fillData)
      }
      this.addRepayList()
    },
    getImageString(images = []) {
      return images && images.length ? `["${images.map(item => item.url).join('","')}"]` : ''
    },

    onCensusNumberYearInput() {
      this.censusNumberYear = this.censusNumberYear.replace(/[^0-9]+/g, '')
      if (this.censusNumberYear.length > 4) {
        const lastChar = this.censusNumberYear[4]
        this.censusNumberYear = this.censusNumberYear.replace(/^(\d{4}).*/, '$1')
        this.$refs.censusNumberSerial.focus()
        if (!this.censusNumberSerial) {
          this.censusNumberSerial = lastChar
        }
      }
      if (this.censusNumberYear.length === 4) {
        const year = +this.censusNumberYear
        if (year > yearNow || year < yearNow - 1) {
          this.$message.error('编号年份必须是今年或去年！')
        }
      }
    },

    onCensusNumberSerialInput() {
      this.censusNumberSerial = this.censusNumberSerial.replace(/[^0-9]+/g, '')
      if (this.censusNumberSerial.length > 3) {
        this.censusNumberSerial = this.censusNumberSerial.replace(/^\d(\d{3}).*/, '$1')
      }
      if (this.censusNumberSerial === '000') {
        this.$message.error('编号必须大于0')
      }
    },

    getFullNumberSerial() {
      return Array(3 - this.censusNumberSerial.length).join('0') + this.censusNumberSerial
    },

    validateCensusNumberFromRemote(num) {
      // eslint-disable-next-line
      return new Promise(async resolve => {
        const [res, err] = await this.$utils.promise(
          this.$api.getData(CREDIT_SERVER, 'credit_level_review', {
            'loan_notice.eq': num,
          })
        )
        if (err) {
          this.$message.error('项目编号远程验证失败！')
          resolve(-1)
        } else if (res && res.data && res.data.length) {
          resolve(res.data.length)
        } else {
          resolve(0)
        }
      })
    },

    // 还款计划
    initDialogMaxHeight() {
      const clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight || window.innerHeight
      this.dialogMaxheight = clientHeight - 300
    },
    showViewRepayList() {
      this.repayVisible = true
      if (!this.viewRepayList.length) {
        this.getRepayList()
      }
    },
    async getRepayList() {
      this.repayLoading = true
      const [res, err] = await this.$utils.promise(
        this.$api.getData(
          CREDIT_SERVER,
          'datum_repay_list',
          {
            'customer_related_id.eq': this.relatedId,
          },
          { pay_time: 'asc' }
        )
      )
      this.repayLoading = false
      this.viewRepayList = ((res && res.data) || []).map(item => {
        item.pay_time = this.$utils.dateFormat(item.pay_time, 'yyyy年MM月dd日')
        return item
      })
      this.viewRepayListError = Boolean(err)
    },
    async addRepayList() {
      if (this.repayListExist) {
        return
      }
      const repayListData = []
      for (const item of this.repayList) {
        if (item.pay_time) {
          repayListData.push({
            customer_related_id: this.relatedId,
            pay_time: item.pay_time,
            is_interest: item.is_interest,
            capital: item.capital,
          })
        }
      }
      if (!repayListData.length) {
        return
      }
      const [, err] = await this.$utils.promise(
        this.$api.addBatch(CREDIT_SERVER, 'datum_repay_list', repayListData)
      )
      if (err) {
        return this.$message.error('生成还款计划失败，请重试')
      }
      this.getRepayList()
    },
    showRepayList() {
      if (this.repayList.length > 1) {
        // 之前修改的
        this.repayVisible = true
        return
      }
      if (!this.fillData.repay_type) {
        return this.$message.warning('请先选择还款设置')
      }
      // 不是按照贷款日期来计划开始时间
      // const startDate = this.repayStart ? new Date(this.repayStart) : ''
      // if (!startDate) {
      //   return this.$message.warning('请先填写贷款日期')
      // }
      const period = +this.repayPeriod || 0
      if (!period) {
        return this.$message.warning('请先填写用款期限')
      }
      this.initRepayList()
      this.repayVisible = true
    },
    onSelectFirstRepayDate(val, index) {
      if (!val || index > 0) {
        return
      }
      this.repayList = [{ ...this.repayList[0] }]
      const startDate = new Date(val)
      const startYear = startDate.getFullYear()
      const startMonth = startDate.getMonth() + 1
      const startDay = startDate.getDate()
      const period = +this.repayPeriod || 0
      for (let i = 1; i < period * 12; i++) {
        let tempMonth = (startMonth + i) % 12
        if (tempMonth === 0) {
          tempMonth = 12
        }
        const tempYear = startYear + Math.floor((startMonth + i) / 12)
        this.repayList.push({
          pay_time: `${tempYear}-${this.autoFillZero(tempMonth)}-${this.autoFillZero(startDay)}`,
          capital: '',
          is_interest: this.repayMonthType ? '1' : tempMonth % 3 === 0 ? '1' : '0',
          canChange: this.repayMonthType ? true : tempMonth % 3 === 0,
        })
      }
    },
    onRepayClose() {
      this.repayVisible = false
    },
    onRepayTypeChange(val) {
      if (this.repayList.length < 2) {
        this.fillData.repay_type = val
        return
      }
      this.repayType = this.fillData.repay_type
      this.$confirm('已经有还款计划，更换还款设置后需要重新生成，确定修改？', '提示', {
        confirmButtonText: '确定修改',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.initRepayList()
          this.repayType = val
          this.fillData.repay_type = val
        })
        .catch(() => {})
    },
    autoFillZero(num) {
      return num > 9 ? num : `0${num}`
    },
    initRepayList() {
      this.repayList = [
        {
          pay_time: '',
          is_interest: '1',
          capital: '',
        },
      ]
    },
    onRepayListDismiss() {
      if (this.repayList.length < 2) {
        this.onRepayClose()
      } else {
        this.$confirm('确定取消还款计划，并重置填写的数据？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.initRepayList()
            this.onRepayClose()
          })
          .catch(() => {})
      }
    },
    onRepayListFinsish() {
      this.repayVisible = false
    },
    onAutoFill(row, index) {
      for (let i = index; i < this.repayList.length; i++) {
        this.repayList[i].capital = row.capital
      }
    },
    isLastMonthAtQuarter(payTime) {
      if (this.repayMonthType || !payTime) {
        return true
      }
      return (new Date(payTime).getMonth() + 1) % 3 === 0
    },
  },
}
</script>
<style scoped lang="scss">
.text-num {
  font-size: 1.25rem;
  font-weight: bold;
}

.table-bordered tr td {
  vertical-align: middle;
}

.span-margin {
  margin-right: 100px;
}

.span-margin-min {
  margin-right: 20px;
}

.input-min {
  width: 100px;
}

.btn-long {
  min-width: 100px;
}

.auto-fill-icon {
  background-color: #ffffee;
  padding: 5px 10px;
  cursor: pointer;
  color: #c0c4cc;
  i.fa {
    font-size: 0.5rem;
  }
}
</style>
